package com.nebula.salary.portal.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nebula.salary.common.constants.Const;
import com.nebula.salary.common.result.ServerResponse;
import com.nebula.salary.common.utils.NumberFormatUtil;
import com.nebula.salary.common.utils.RedisUtil;
import com.nebula.salary.common.utils.SecurityUtil;
import com.nebula.salary.model.dto.PageDto;
import com.nebula.salary.model.pojo.Salary;
import com.nebula.salary.model.pojo.User;
import com.nebula.salary.model.vo.LoginUser;
import com.nebula.salary.model.vo.PageResult;
import com.nebula.salary.model.vo.SalaryVo;
import com.nebula.salary.portal.service.IBenefitsService;
import com.nebula.salary.portal.service.ISalaryService;
import com.nebula.salary.portal.service.IUserService;
import com.nebula.salary.portal.service.IWorkOvertimeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 工资统计
 *
 * @author codex
 * @since 2022-02-20
 */
@RestController
@Api(tags = "工资统计")
@RequestMapping("/salary/analyze")
public class AnalyzeController {
    
    @Resource
    private ISalaryService salaryService;
    
    @Resource
    private IBenefitsService benefitsService;
    
    @Resource
    private IUserService userService;

    @Resource
    private IWorkOvertimeService workOvertimeService;
    
    @Resource
    private RedisUtil redisUtil;
    
    @ApiOperation("节日福利年度统计")
    @GetMapping("/benefits-year-bar")
    public ServerResponse<List<Map<String, BigDecimal>>> getBenefitsYearBar() {
        List<Map<String, BigDecimal>> result = benefitsService.getBenefitsYearBar(SecurityUtil.getUserId());
        return ServerResponse.createBySuccess(result);
    }
    
    @ApiOperation("工资年度统计")
    @GetMapping("/salary-year-pie")
    public ServerResponse<List<Map<String, BigDecimal>>> getSalaryYearPie() {
        
        List<Map<String, BigDecimal>> result = salaryService.getSumSalaryGroupByYear(SecurityUtil.getUserId());
        
        return ServerResponse.createBySuccess(result);
    }
    
    @ApiOperation("工资月度统计")
    @GetMapping("/salary-month-line/{yearCount}")
    public ServerResponse<List<Map<String, Object>>> getSalary(
            @ApiParam(value = "查询几年，0代表1年", required = true)
            @PathVariable Integer yearCount) {
        
        if (yearCount > 9 || yearCount < -1) {
            return ServerResponse.createByErrorMessage("最多查询10年的数据");
        }
        
        List<Salary> salaries = salaryService.getSalaryByYearCount(yearCount);
        
        Integer year = 0;
        List<Map<String, Object>> list = Lists.newArrayList();
        BigDecimal[] bigDecimals = null;
        for (Salary salary : salaries) {
            Map<String, Object> dataMap = Maps.newLinkedHashMap();
            boolean a = false;
            if (!year.equals(salary.getIssueYear())) {
                year = salary.getIssueYear();
                dataMap.put("year", year);
                a = true;
                bigDecimals = new BigDecimal[12];
                Arrays.fill(bigDecimals, BigDecimal.valueOf(0.1));
            }
            assert bigDecimals != null;
            bigDecimals[salary.getIssueMonth() - 1] = salary.getSalary();
            if (a) {
                dataMap.put("salary", bigDecimals);
                list.add(dataMap);
            }
        }
        
        return ServerResponse.createBySuccess(list);
    }
    
    @ApiOperation(value = "首页面板数据")
    @GetMapping("/panel-data")
    public ServerResponse<Map<String, Object>> getPanelData() {
        
        // 工资总计
        BigDecimal sumSalary = salaryService.getSum();
        
        // 节日福利总计
        BigDecimal sumBenefit = benefitsService.getSum();
        
        Map<String, Object> resultMap = Maps.newLinkedHashMap();
        resultMap.put("sumSalary", NumberFormatUtil.numberToString(sumSalary));
        resultMap.put("sumBenefit", NumberFormatUtil.numberToString(sumBenefit));
        
        // 判断用户权限
        Long userId = SecurityUtil.getUserId();
        if (User.isAdmin(userId) || userService.getById(userId).getRoleId() <= 1002) {
            // 查询总用户数
            int count = userService.count();
            resultMap.put("totalUser", NumberFormatUtil.numberToString(BigDecimal.valueOf(count)));
        }

        // 当年加班天数
        ServerResponse<BigDecimal> count = workOvertimeService.getYearCount();
        resultMap.put("days", NumberFormatUtil.numberToString(count.getData()));

        return ServerResponse.createBySuccess(resultMap);
    }
    
    @ApiOperation(value = "工资统计", notes = "工资统计")
    @GetMapping("/")
    public ServerResponse<PageResult> analyze(PageDto pageDto) {
        
        LoginUser loginUser = SecurityUtil.getLoginUser();
        PageResult pageResult = redisUtil.getObject(Const.ANALYZE_RESULT_KEY + loginUser.getUuid());
        if (pageResult == null) {
            return salaryService.analyze(pageDto);
        }
        return ServerResponse.createBySuccess(pageResult);
    }
    
}
